import React, { useState, useContext } from "react";
import { useNavigate } from "react-router-dom";
import { Button, Checkbox, Form, Input, message } from "antd";
import "../../flexble";
import "../css/Login.css";
import axiosInstance from "../utils/axiosInstance";
import { AuthContext } from "../utils/AuthContext";
import apiConfigManager from "../../utils/apiConfigManager";

const App = () => {
  const navigate = useNavigate();
  const { login } = useContext(AuthContext);
  var [login_type_key, set_login_type_key] = useState("phone");
  const [form] = Form.useForm();
  const [currentApi, setCurrentApi] = useState('');

  // 获取当前API配置用于调试
  React.useEffect(() => {
    const api = apiConfigManager.getCurrentApi();
    setCurrentApi(api.url);
    console.log('当前API地址:', api.url);
  }, []);

  // 手机号验证规则
  const phoneValidationRules = [
    { required: true, message: "请输入手机号" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号格式",
    },
  ];

  // 邮箱验证规则
  const emailValidationRules = [
    { required: true, message: "请输入邮箱" },
    {
      type: "email",
      message: "请输入正确的邮箱格式",
    },
  ];

  // 密码验证规则
  const passwordValidationRules = [
    { required: true, message: "请输入密码" },
    {
      pattern: /^.{6,18}$/,
      message: "密码长度必须在6-18位之间",
    },
  ];



  

  const handleGetCode = () => {
    const phone = form.getFieldValue("phone");
    const email = form.getFieldValue("email");
    console.log(phone, "phone");
    console.log(email, "email");
    console.log(login_type_key, "login_type_key");

    if (login_type_key == "phone") {
      if (!phone) {
        message.error("请先输入手机号");
        return;
      }
      // 验证手机号格式
      if (!/^1[3-9]\d{9}$/.test(phone)) {
        message.error("手机号格式错误");
        return;
      }
      axiosInstance
        .post("/ltc/sendcode", { phone })
        .then((res) => {
          message.success(res.data.msg);
        })
        .catch((err) => {
          message.error("获取验证码失败");
        });
    } else {
      if (!email) {
        message.error("请先输入邮箱");
        return;
      }
      // 验证邮箱格式
      if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
        message.error("邮箱格式错误");
        return;
      }
      axiosInstance
        .post("/ltc/sendcode", { email })
        .then((res) => {
          message.success(res.data.msg);
        })
        .catch((err) => {
          message.error("获取验证码失败");
        });
    }
  };

  const onFinish = async (values) => {
    console.log('注册请求 - 当前API地址:', currentApi);
    console.log('注册数据:', values);
    
    if (login_type_key == "phone") {
      // 验证手机号格式
      if (!values.phone || !/^1[3-9]\d{9}$/.test(values.phone)) {
        message.error("手机号格式错误");
        return;
      }
      
      // 验证密码格式
      if (!values.password || !/^.{6,18}$/.test(values.password)) {
        message.error("密码格式错误，长度必须在6-18位之间");
        return;
      }
      
      // 验证密码一致性
      if (values.password != values.password2) {
        message.error("密码不一致");
        return;
      }
      
      values.img =
        "https://ts1.tc.mm.bing.net/th/id/OIP-C.SWWmUtJk_k7PS8U6DyrxQQAAAA?w=211&h=211&c=8&rs=1&qlt=90&o=6&pid=3.1&rm=2";
      let res = await axiosInstance.post("/ltc/createuser", values);
      console.log(values);

      if (res.data.code == 200) {
        message.success("注册成功");
        navigate("/login");
      } else {
        message.error(res.data.msg);
      }
    } else {
      // 验证邮箱格式
      if (!values.email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values.email)) {
        message.error("邮箱格式错误");
        return;
      }
      
      // 验证密码格式
      if (!values.password || !/^.{6,18}$/.test(values.password)) {
        message.error("密码格式错误，长度必须在6-18位之间");
        return;
      }
      
      // 验证密码一致性
      if (values.password != values.password2) {
        message.error("密码不一致");
        return;
      }
      
      values.img =
        "https://ts1.tc.mm.bing.net/th/id/OIP-C.SWWmUtJk_k7PS8U6DyrxQQAAAA?w=211&h=211&c=8&rs=1&qlt=90&o=6&pid=3.1&rm=2";
      let res = await axiosInstance.post("/ltc/createuser", values);
      console.log(res.data, "res.data");

      if (res.data.code == 200) {
        message.success("注册成功");
        navigate("/login");
      } else {
        message.error(res.data.msg);
      }
    }
  };
  return (
    <>
      <div className="login_type_div">
        <span
          className={`login_type ${login_type_key === "phone" ? "login_type_active" : ""}`}
          onClick={() => {
            set_login_type_key("phone");
          }}
        >
          手机号注册
        </span>
        <span
          className={`login_type ${login_type_key === "email" ? "login_type_active" : ""}`}
          onClick={() => {
            set_login_type_key("email");
          }}
        >
          邮箱注册
        </span>
      </div>
      <Form
        form={form}
        name="basic"
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        style={{ width: "80%", height: "15rem", textAlign: "center" }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        autoComplete="off"
      >
        {/* 手机验证码登录 */}
        {login_type_key == "phone" ? (
          <>
            <Form.Item
              label="手机号"
              name="phone"
              rules={phoneValidationRules}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="验证码"
              name="code"
              rules={[{ required: true, message: "请输入验证码" }]}
            >
              <div style={{ display: "flex", justifyContent: "space-between" }}>
                <Input style={{ width: "65%" }} />
                <button
                  type="button"
                  className="login_code_button"
                  onClick={handleGetCode}
                >
                  获取验证码
                </button>
              </div>
            </Form.Item>
            <Form.Item
              label="密码"
              name="password"
              rules={passwordValidationRules}
            >
              <Input.Password />
            </Form.Item>
            <Form.Item
              label="确认密码"
              name="password2"
              rules={[
                { required: true, message: "请确认密码" },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('password') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('两次输入的密码不一致'));
                  },
                }),
              ]}
            >
              <Input.Password />
            </Form.Item>
          </>
        ) : null}

        {/* 邮箱验证码登录 */}
        {login_type_key == "email" ? (
          <>
            <Form.Item
              label="邮箱"
              name="email"
              rules={emailValidationRules}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="验证码"
              name="code"
              rules={[{ required: true, message: "请输入验证码" }]}
            >
              <div style={{ display: "flex", justifyContent: "space-between" }}>
                <Input style={{ width: "65%" }} />
                <button
                  type="button"
                  className="login_code_button"
                  onClick={handleGetCode}
                >
                  获取验证码
                </button>
              </div>
            </Form.Item>
            <Form.Item
              label="密码"
              name="password"
              rules={passwordValidationRules}
            >
              <Input.Password />
            </Form.Item>
            <Form.Item
              label="确认密码"
              name="password2"
              rules={[
                { required: true, message: "请确认密码" },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('password') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('两次输入的密码不一致'));
                  },
                }),
              ]}
            >
              <Input.Password />
            </Form.Item>
          </>
        ) : null}

        <Form.Item label={null}>
          <div style={{ display: "flex", justifyContent: "space-around" }}>
            <Button type="primary" htmlType="submit">
              注册
            </Button>
            <Button
              type="primary"
              htmlType="submit"
              onClick={() => {
                navigate("/login");
              }}
            >
              返回登录
            </Button>
          </div>
        </Form.Item>
      </Form>
    </>
  );
};
export default App;
